package com.yuns.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yuns.jwt.JWTToken;
import com.yuns.jwt.JWTUtil;
import com.yuns.model.entity.SysPermission;
import com.yuns.model.entity.SysRole;
import com.yuns.model.entity.SysUser;
import com.yuns.model.service.SysPermissionService;
import com.yuns.model.service.SysRoleService;
import com.yuns.model.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class MyShiroRealm extends AuthorizingRealm {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysPermissionService isys_permissionService;

    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取令牌对应的登录名
        String name = JWTUtil.getUsername(principalCollection.toString());
        //添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //  根据用户  找到对应的 角色
        Map<String,String> map = new HashMap<String,String>();
        map.put("account",name);
        List<SysRole> roleList = sysRoleService.selectRoleByName(map);
        List<SysPermission> permissionList = permissionService.selectPermissionByName(map);

        for (SysRole strRole : roleList) {
            //添加角色
            simpleAuthorizationInfo.addRole(strRole.getRoleName());
            log.info("角色 : .........................." + strRole.getId()+"......................" +strRole.getRoleName() );
        }
        log.info("权限 : .........................." +permissionList.get(0).getName());

        for (SysPermission permission : permissionList) {
            log.info("权限 : .........................." + permission.getName());
            //添加权限
            simpleAuthorizationInfo.addStringPermission(permission.getName());
        }

        log.info("进行授权.................");
        return simpleAuthorizationInfo;

    }

    //用户认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken atoken) throws AuthenticationException {

        String token = (String) atoken.getCredentials();
        log.info("token ------------- : " + token);
        // 解密获得username，用于和数据库进行对比
        String userName = JWTUtil.getUsername(token);
        log.info("phone ------------- : " + userName);
        if (userName == null) {
            throw new AuthenticationException("token不可用！");
        }
        //  查询用户
        SysUser user = sysUserService.selectOne(new EntityWrapper<SysUser>().eq("account",userName));


        if (user == null) {
            throw new UnknownAccountException("用户不存在！");
        }

        /*if (! JWTUtil.verify(token, userName, user.getPassword())) {
            throw new UnsupportedTokenException("用户名或密码不存在");
        }*/
        /**
         * 用户权限
         */
        List<SysPermission> sysPermissions = isys_permissionService.findTree(2);
        user.setPermissions(sysPermissions);

        log.info("认证通过...............");
        return new SimpleAuthenticationInfo(user, token, this.getName());
    }
}
